Why Formal Verification is Critical:
Advantages of Dafny:
Pre-requisites:
Installation Steps:
Install .NET 6 SDK:
sudo apt install -y dotnet-sdk-6.0
brew install --cask dotnet-sdk
Install Dafny via .NET:
dotnet tool install -g dafny
Verify Installation:
dafny --version
Optional: Install Dafny Extension in Visual Studio Code:
Dafny Program Structure:
Formal Verification:
Key Concepts:
Verification Workflow:
Problem Statement:
Basic Dafny Method:
method Transfer(sender: int, receiver: int, amount: int)
requires sender != receiver
requires amount > 0
requires balance[sender] >= amount
modifies balance
ensures balance[sender] == old(balance[sender]) - amount
ensures balance[receiver] == old(balance[receiver]) + amount
{
balance[sender] := balance[sender] - amount;
balance[receiver] := balance[receiver] + amount;
}
Explanation:
Defining Preconditions and Postconditions:
Defining Invariants (optional):
method Transfer(sender: int, receiver: int, amount: int)
requires sender != receiver
requires amount > 0
requires balance[sender] >= amount
modifies balance
ensures balance[sender] == old(balance[sender]) - amount
ensures balance[receiver] == old(balance[receiver]) + amount
ensures forall i :: 0 <= i < balance.Length ==> balance[i] >= 0
{
balance[sender] := balance[sender] - amount;
balance[receiver] := balance[receiver] + amount;
}
Explanation:
Verify the Contract:
dafny contract.dfy
Check Verification Output:
Interpret Dafny’s Output: